
package com.windgo.config.realm;

import com.windgo.bean.MarketAdmin;
import com.windgo.bean.MarketAdminExample;
import com.windgo.bean.MarketUser;
import com.windgo.bean.MarketUserExample;
import com.windgo.mapper.MarketAdminMapper;
import com.windgo.mapper.MarketUserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * 提供认证信息和授权信息
 *
 * @author 张林浩
 * @since 2022/10/11 21:27
 */
@Component
public class CustomRealm extends AuthorizingRealm {
    //通常把doGetAuthenticationInfo方法放在上面  先认证后授权

    @Autowired
    MarketAdminMapper mapper;
    @Autowired
    MarketUserMapper userMapper;

    //该方法的形参 → 来源于subject的login方法
    // 传入该值，为了根据用户名查询到该用户在系统中的密码（数据库中维护） → 来构造认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //根据authenticationtoken中传入的用户名信息查询出该用户在数据库中的信息。
        String type = ((MarketToken) authenticationToken).getType();
        //TODO 测试中

         UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();

//        String username = (String) authenticationToken.getPrincipal();
//
        if ("admin".equals(type)) {
            //根据username查询数据库中对应password
            // String password = selectPasswordByUsername(username);
            MarketAdminExample example = new MarketAdminExample();
            example.createCriteria().andUsernameEqualTo(username);
            List<MarketAdmin> marketAdmins = mapper.selectByExample(example);
            if (marketAdmins.size() == 1) {
                MarketAdmin marketAdmin = marketAdmins.get(0);
                //构造认证信息时，可以放入你需要的用户信息，而你放入的用户信息，可以作为principals
                //第二个值是真实的密码，会和AuthenticationToken中的password作比较。
                return new SimpleAuthenticationInfo(marketAdmin, marketAdmin.getPassword(), getName());
            }
        } else if ("wx".equals(type)) {
            MarketUserExample example = new MarketUserExample();
            example.createCriteria().andUsernameEqualTo(username);
            List<MarketUser> marketUsers = userMapper.selectByUserExample(example);
            if (marketUsers.size() == 1) {
                MarketUser marketUser = marketUsers.get(0);

                return new SimpleAuthenticationInfo(marketUser, marketUser.getPassword(), getName());
            }
        }


        return null;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        MarketAdmin primaryPrincipal = (MarketAdmin) principalCollection.getPrimaryPrincipal();
        List<String> permissions = getPermissionsByUsername(primaryPrincipal.getUsername());

        // 根据用户信息拿到所有的权限（数据库）
        // doGetAuthenticationInfo方法返回值的第一个参数就是用户信息
        // 在第21行代码放入的是字符串类型的Principal信息，取出的时候就可以以字符串格式取出
        //String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        // List<String> permissions = getPermissionsByUsername(primaryPrincipal);

        //将授权信息放进去
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    // private String selectPasswordByUsername(String username) {
    //     // 应该通过MyBatis根据用户名查询获得结果
    //
    //     return "123456";
    // }

    private List<String> getPermissionsByUsername(String username) {
        // 应该通过MyBatis根据用户名查询获得结果
        //先获取用户所有的role_ids
        //Integer[] integers = mapper.getRoleIdsByUsername(username);
        MarketAdmin marketAdmin = mapper.getRoleIdsByUsername2(username);
        Integer[] roleIds = marketAdmin.getRoleIds();
        System.out.println(roleIds.toString());

        // String roleIds = mapper.getRoleIdsByUsername1(username);
        // roleIds.replace("]","");
        // // char[] chars = roleIds.toCharArray();
        // // for (char aChar : chars) {
        // //     Integer.parseInt(aChar)
        // // }
        // String[] split = roleIds.split(",");
        // for (String s : split) {
        //     Integer.parseInt(s);
        // }

        List<String> strings = new ArrayList<>();
        for (Integer integer : roleIds) {
            List<String> strings1 = mapper.getPermissionsByRoleId(integer);
            strings.addAll(strings1);
        }
        return strings;

    }
}
